package com.dylan.jetcache.service.user;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.RefreshPolicy;
import com.alicp.jetcache.anno.CacheRefresh;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CreateCache;
import com.dylan.jetcache.entity.User;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangshaojian
 * @date 2022/7/8 14:26
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @CreateCache(name = "users", keyConvertor = "#key", expire = 100)
    private Cache<String, User> userCache;

    @Override
    @CacheRefresh(refresh = 5, stopRefreshAfterLastAccess = 30)
    @Cached(name = "users", key = "':all'", expire = 10, cacheType = CacheType.BOTH)
    public List<User> findAll() {
        log.info("进入数据库查询！！！");
        return Lists.newArrayList(new User().setName("李四").setAge(2), new User().setName("张三").setAge(1));
    }

    @Override
    public void save(User user) {
        userCache.config().setRefreshPolicy(RefreshPolicy.newPolicy(1, TimeUnit.MINUTES));
        userCache.put(user.getName(), user);
    }
}
